#! /usr/bin/python
# -*- coding:  utf-8 -*-
#
# accoufer : cgi script for creating/editing a new client
# 
# Copyright S.Keim 2011
# Available under the MIT licence see the COPYING file

import accoufer
import shelve
import cgi

def run():
    class param:
        url = ""
        
    # logged user
    login, user = accoufer.userCookie()

    # extract parameters
    form = cgi.FieldStorage()
    if "url" not in form:
        print accoufer.HTML%( "Client", FORM%param.__dict__)
        return 
    try:
        param.url = form["url"].value  # client service url
    except KeyError:
        return error("missing parameter")
 
    # read client accoufer.txt
    clients = shelve.open(accoufer.CLIENT_PATH)
    client_data = {}
    if not accoufer.update_client(param.url, client_data):
        return error( "Check client protocol")

    param.url = client_data[accoufer.URL_KEY] # canonical url
    
    # check that this is not our url ...
    if param.url == accoufer.SERVICE_URL:
         return error("Can't register myself as client")  
    
    if param.url not in clients:
        param.name = client_data[accoufer.NAME_KEY]
        clientcount = clients[accoufer.COUNT_KEY]+1
        clients[accoufer.COUNT_KEY] = clientcount
        clientref = str(clientcount)
        offers = shelve.open(accoufer.offerpath(clientref), 'c')
        offers.update(client_data)
        offers[accoufer.COUNT_KEY] = 0
        clients[param.url] = clientref, param.name, param.url
    
    # ok
    print accoufer.HTML%( "Response success", SUCCESS%client_data ) 
   
def error(txt):
    param.err = txt
    msg = ERROR%param.__dict__
    print accoufer.HTML%("Error", msg)    
    
  
IN_FORM = """<form method=post action="./xnewclient">
Client url: <input name="url" value="%(url)s"><br/>
<input type="submit" value="Run"/></form><p/>
</table>
"""

ERROR = "<h1>Error</h1><b>%(err)s</b><p/>"+IN_FORM

FORM = "<h1>New service</h1>"+IN_FORM

SUCCESS = """<h1>New service</h1><a href="%(url_)s">%(name_)s</a> has been imported with success<hr/> <a href="./index.html">Start</a>"""

if __name__=="__main__":
    run()
